package com.studyinghome.handler;

import cn.hutool.core.util.StrUtil;
import com.studyinghome.aop.RateLimit;
import com.studyinghome.config.RedisLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Leslie (panxiang_work@163.com)
 * @website https://www.studyinghome.com
 * @create 2023-04-09 15:35
 */
@Component
@Aspect
public class RateLimitAspect {
    @Autowired
    private RedisLimit redisLimit;


    @Around("@annotation(rateLimit)")
    public Object doAround(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        if (StrUtil.isBlank(rateLimit.name())) {
            throw new IllegalArgumentException("限流的值不能为null或者空字符串");
        }
        if (redisLimit.limit(rateLimit.name(), rateLimit.limit(), rateLimit.timeout(), rateLimit.ipLimit(), rateLimit.ipCount(), rateLimit.ipTimeout())) {
            return joinPoint.proceed();
        } else {
            throw new RuntimeException("请求过于频繁，请稍后再试！");
        }
    }
}
